<template>
  <div v-show="isStatic">
    <div class="flex gap-2">
      <el-tag :type="categoryTagType" size='large' round @click="cancelGroupByCategory">类别分组</el-tag>
      <el-tag :type="brandTagType" size='large' round @click="cancelGroupByBrand" style="margin-left: 10px">品牌分组
      </el-tag>
      <el-button plain sizprimarye="small" @click="clearGroup" style="margin-left: 10px">重置</el-button>
    </div>

    <!-- 商品列表表格 -->
    <el-table :data="products" style="width: 100%">
      <el-table-column prop="brand_id" label="品牌序号" width="80"
                       v-if="groupBy[0] === 'brand_id'||groupBy.length === 2"></el-table-column>
      <el-table-column prop="category_id" label="分类序号" width="80"
                       v-if="groupBy[0] === 'category_id'||groupBy.length === 2"></el-table-column>
      <el-table-column label="平均市场价" width="120">
        <template #default="scope">
          {{ scope.row.avg_market_price / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="平均销售价" width="120">
        <template #default="scope">
          {{ scope.row.avg_selling_price / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="最高市场价" width="120">
        <template #default="scope">
          {{ scope.row.max_market_price / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="最高销售价" width="120">
        <template #default="scope">
          {{ scope.row.max_selling_price / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="最低市场价" width="120">
        <template #default="scope">
          {{ scope.row.min_market_price / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="最低销售价" width="120">
        <template #default="scope">
          {{ scope.row.min_selling_price / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column prop="product_count" label="产品数量" width="100"></el-table-column>
    </el-table>
    <el-button type="primary" @click="changeProduct" style="margin-top: 10px">返回</el-button>
  </div>
  <div v-show="!isStatic">

    <!-- 添加商品按钮 -->
    <div>
      <el-button type="primary" @click="handleAdd" style="margin-bottom: 10px">添加商品</el-button>
      <el-button type="success" @click="changeGroup" style="margin-bottom: 10px">分组统计</el-button>
      <div class="mt-4">
        <el-input
            v-model="searchQuery"
            style="max-width: 600px"
            placeholder="请按规则输入查询内容"
            class="input-with-select"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="请选择查询规则" style="width: 115px">
              <el-option label="按商品名称或者关键字查询" value="1"/>
              <el-option label="按价格区间查询，~，例如，小于500为~500，大于500为500~,大于200小于500为200~500" value="2"/>
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="search"/>
          </template>
        </el-input>
        <el-button plain size="small" @click="clearSearch" style="margin-left: 10px">重置</el-button>
      </div>
    </div>

    <!-- 商品列表表格 -->
    <el-table :data="products" style="width: 100%">
      <el-table-column prop="productId" label="序号" width="80"></el-table-column>
      <el-table-column prop="productName" label="商品名称" width="200"></el-table-column>
      <el-table-column label="商品图片" width="100">
        <template #default="scope">
        <img :src="scope.row.productImg" alt="商品图片" style="width: 100px; height: 100px">
        </template>
      </el-table-column>
      <el-table-column prop="modelNumber" label="型号" width="150"></el-table-column>
      <el-table-column prop="unit" label="单位" width="80"></el-table-column>
    <el-table-column label="市场价" width="100">
        <template #default="scope">
          {{ scope.row.marketPrice / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="销售价" width="100">
        <template #default="scope">
          {{ scope.row.sellingPrice / 100 }} 元
        </template>
      </el-table-column>
            <el-table-column label="成本价" width="100">
        <template #default="scope">
          {{ scope.row.costPrice / 100 }} 元
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="totalProducts"
        @current-change="handlePageChange"
        style="margin-top: 10px"
    />

    <addProductDrawer :drawer-visible="isDrawerVisible"
                      @update:drawerVisible="val => isDrawerVisible = val"
                      @formSubmitted="fetchProducts"></addProductDrawer>
    <editProductDialog :product="selectedProduct"
                       :drawer-visible="isEditDrawerVisible"
                       @update:drawerVisible="val => isEditDrawerVisible = val"
                       @formSubmitted="fetchProducts"></editProductDialog>
  </div>
</template>
<script setup>
import {onMounted, ref} from 'vue';
import {ElButton, ElMessage, ElMessageBox} from 'element-plus';
import {Search} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router';
import {deleteProduct} from '@/api/product.js';
import addProductDrawer from '@/components/drawer/addProductDrawer.vue'
import {
  getProductByMarkerPriceScope_supplier,
  getProductGroup,
  getSupplierProduct,
  getSupplierProductLikeName
} from '@/api/supplier.js'
import editProductDialog from '@/components/dialog/editProductDialog.vue'; // 假设路径正确
const searchQuery = ref('')
const groupBy = ref(['brand_id', 'category_id']);
const router = useRouter();
const products = ref([]);
const categoryTagType = ref('primary')
const brandTagType = ref('primary')
const currentPage = ref(1);
const select = ref('')
const pageSize = 3;
const isStatic = ref(false);
const totalProducts = ref(0);
const isDrawerVisible = ref(false);
import {supplierTokenStore} from "@/store/tokenStore.js";

const cancelGroupByCategory = async () => {
  if (groupBy.value.length > 1) {
    categoryTagType.value = 'info'
    groupBy.value = groupBy.value.filter(item => item !== 'category_id');
    // console.log(groupBy.value)
    fetchStatic();
  } else {
    ElMessage.error("至少要选择一个分组条件,恢复原始数据请按重置")
  }
}
const cancelGroupByBrand = async () => {
  if (groupBy.value.length > 1) {
    brandTagType.value = 'info'
    groupBy.value = groupBy.value.filter(item => item !== 'brand_id');
    // console.log(groupBy.value)
    fetchStatic();
  } else {
    ElMessage.error("至少要选择一个分组条件,恢复原始数据请按重置")
  }
}
const clearGroup = () => {
  groupBy.value = ['brand_id', 'category_id'];
  categoryTagType.value = 'primary'
  brandTagType.value = 'primary'
  fetchStatic()
}
const changeGroup = () => {
  isStatic.value = !isStatic.value
  fetchStatic()
}
const changeProduct = () => {
  isStatic.value = !isStatic.value
  fetchProducts()
}
const search = () => {
  if (searchQuery.value !== '' && select !== '') {
    if (select.value === '1') {
      getLikeName()
    } else if (select.value === '2') {
      getPriceScope()
    } else {
      ElMessage.error('请选择查询规则')
    }
  } else {
    ElMessage.error('请输入查询内容')
  }
}
//模糊查条件
const getLikeName = async () => {
  const response = await getSupplierProductLikeName(
      currentPage.value, pageSize, searchQuery.value)
  products.value = response.list;
  totalProducts.value = response.totalNum;
}
const getPriceScope = async () => {
  const priceScopeList = searchQuery.value.split('~')
  if (searchQuery.value.includes('~')) {
    if (priceScopeList[0] !== '' && priceScopeList[1] !== '') {
      const response = await getProductByMarkerPriceScope_supplier(currentPage.value, pageSize,
          priceScopeList[0], priceScopeList[1])
      products.value = response.list;
      totalProducts.value = response.totalNum;
    } else if (priceScopeList[0] === '') {
      const response = await getProductByMarkerPriceScope_supplier(currentPage.value, pageSize,
          -1, priceScopeList[1])
      products.value = response.list;
      totalProducts.value = response.totalNum;
    } else if (priceScopeList[1] === '') {
      const response = await getProductByMarkerPriceScope_supplier(currentPage.value, pageSize,
          priceScopeList[0], -1)
      products.value = response.list;
      totalProducts.value = response.totalNum;
    }
  } else {
    ElMessage.error('请按规则输入查询内容，是否缺失了~')
  }
}
const clearSearch = () => {
  searchQuery.value = '';
  fetchProducts();
}
const handleAdd = () => {
  isDrawerVisible.value = true;
};

// 新增两个变量用于控制编辑对话框的状态和所选商品
const isEditDrawerVisible = ref(false);
const selectedProduct = ref(null);

// 更新 handleEdit 方法
const handleEdit = (product) => {
  // console.log('Selected product:', product)
  selectedProduct.value = product;
  isEditDrawerVisible.value = true;
};
//获取分组数据
const fetchStatic = async () => {
  products.value = await getProductGroup(groupBy.value);
  // console.log(products.value)
}
//挂载函数
onMounted(() => {
  if (supplierTokenStore().supplierToken !== '') {
    fetchProducts();
  }
});

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchProducts();
};
const fetchProducts = async () => {
  const response = await getSupplierProduct(currentPage.value, pageSize);
  products.value = response.list;
  totalProducts.value = response.totalNum;
};

const handleDelete = (product) => {
  ElMessageBox.confirm('确认删除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let productIds = [product.productId]
    // 删除商品逻辑
    await deleteProduct(productIds)
    fetchProducts();
    ElMessage.success('删除成功');
  }).catch(() => {
  });
};

</script>

<style scoped>
.el-button {
  margin-right: 10px;
}
</style>